﻿<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Stock History.aspx.cs" Inherits="StockHistory" EnableViewState="true" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
    <script src="Scripts/dist/jquery.js" type="text/javascript"></script>
    <script src="Scripts/dist/jquery.min.js" type="text/javascript"></script>
    <script src="Scripts/dist/jquery.jqplot.min.js" type="text/javascript"></script>
    <link href="Scripts/dist/jquery.jqplot.css" rel="stylesheet" type="text/css" />
    <script src="Scripts/dist/plugins/jqplot.highlighter.min.js" type="text/javascript"></script>
    <script src="Scripts/dist/plugins/jqplot.cursor.min.js" type="text/javascript"></script>
    <script src="Scripts/dist/plugins/jqplot.dateAxisRenderer.min.js" type="text/javascript"></script>
    <script src="Scripts/dist/plugins/jqplot.ohlcRenderer.min.js" type="text/javascript"></script>
    <script src="Scripts/dist/plugins/jqplot.pointLabels.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="jqueryDatepick4.0.6/jquery.datepick.js"></script>
    <style type="text/css">@import "jqueryDatepick4.0.6/jquery.datepick.css";
    .style133
    {
        color: #000000;
    }
    .style134
    {
        font-size: small;
    }
        .style135
        {
            width: 473px;
        }
        .style136
        {
            font-size: 1.5em;
        }
    </style>

    <script language="JavaScript">
        var chart;
        var divToBeWorkedOn = 'chart2';
        var shareCompanyDropdown = '#<%= DropDownListComName.ClientID %>';
        var radioButtonType = '#<%= RadioButtonListType.ClientID %>';
        var zoomed = false;
        var zoomedOut = false;

        $(document).ready(function () {

        /*
            $(shareCompanyDropdown).change(function() {

            if( $(shareCompanyDropdown + " option:selected").val() != "0")
                drawGraph();

            else
                 $(divToBeWorkedOn).html('');

                return false;
            }) //Close $(shareCompanyDropdown).change(function() 
            */
           

        });  // Close $(document).ready(function () {

        function checkZoom() { 
            $.jqplot.postDrawHooks.push(zoomHandler);
        }

        function drawGraph()
        {
            var selected = $(shareCompanyDropdown + " option:selected").val();
            var graph = $('[id*=RadioButtonListType]').find('input:checked').val(); 
            var startDate = $('[id*=txtStartDate]').val(); 
            var endDate = $('[id*=txtEndDate]').val(); 

            if(graph == "Graph" && selected != "0")
            {
                $('#' + divToBeWorkedOn).load(showGraph(selected, startDate, endDate));  
                //checkZoom();
            }
            else 
            {
                    $(divToBeWorkedOn).html('');
            }
        }

        function zoomHandler() {

           var c = this.plugins.cursor;

           if(c._zoom.zooming) {
                zoomed = true;
                zoomedOut = true;
           } else {
              if (zoomedOut == true)
              {
                $('#' + divToBeWorkedOn).load(showGraph($(shareCompanyDropdown + " option:selected").val())); 
                zoomedOut = false;
              } 
              zoomed = false;                  
           }
        }

        function showGraph(selected, startDate, endDate) { 
            
            var webMethod = 'WebService.asmx/DisplayStockHistory';
            var gameID = <%= Session["GameID"].ToString().ToLower() %>;
            var parameters = "{'shareSymbol':'" + selected + "', 'gameID':'" + gameID + "', 'startDate':'" + startDate + "', 'endDate':'" + endDate + "'}";
            var line = [];
            var min = '';
            var max = '';
            var interval;

            $.ajax({
                type: "POST",
                url: webMethod,
                data: parameters,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
               
                    var stocks = response.d;
                    if(stocks != null)
                    {
                        for (var i = 0; i < stocks.length; ++i) {
                            var stock = stocks[i];

                            if(i == 0)
                            {
                                min = stock.Date;
                                var actualDate = new Date(min); // convert to actual date
                                var newDate = new Date(actualDate.getFullYear(), actualDate.getMonth(), actualDate.getDate()-1);
                                min = newDate;
                            }

                            if ((i + 1) == stocks.length)
                            {
                                max = stock.Date;
                                var actualDate = new Date(max); // convert to actual date
                                var newDate = new Date(actualDate.getFullYear(), actualDate.getMonth(), actualDate.getDate()+1);
                                max = newDate;
                            }

                            var row2 = [stock.Date, stock.Open];
                            line.push(row2)
                        } //Close For loop

                        //Clearing Memory
                        if (chart != null) 
                        {
                            $('#' + divToBeWorkedOn + ' *').unbind(); // iexplorer
                            $(divToBeWorkedOn).html('');
                            $(divToBeWorkedOn).remove();
                            chart.destroy();
                            CollectGarbage();
                        }

                        var diff =  Math.floor(( Date.parse(max) - Date.parse(min) ) / 86400000);

                        if (diff >= (365 * 10))
                            interval = '6 months';

                        else if (diff >= (365 * 5))
                            interval = '3 month';

                        else if (diff > (365 * 2 ))
                            interval = '2 month';

                       else if (diff > 365)
                            interval = '1 month';

                        else if (diff > 180)
                            interval = '2 week';

                        else if (diff > 30)
                            interval = '1 week';

                        else
                            interval = '1 day';


                        if (line.length > 0) {
                            chart = $.jqplot(divToBeWorkedOn, [line], {
                            title: selected,
                            axes: {
                                xaxis: {
                                    renderer: $.jqplot.DateAxisRenderer,
                                    tickOptions:{formatString:'%b %e'}, 
                                    min: min,
                                    max: max,
                                    tickInterval: interval,
                                },
                                yaxis: {
                                    tickOptions: {
                                        formatString: '$%.2f'
                                    }
                                }
                            },
                            cursor: {
                                show: true,
                                zoom: true,
                                tooltipLocation: 'sw',
                                style: 'pointer'
                            },
                            highlighter: {
                                show: true
                            },
                            seriesDefaults: {
                                showMarker:true,
                                pointLabels: {
                                show: false,
                                edgeTolerance: 5
                            }},
                            });
                          
                            chart.replot(); 
                        }
                    }
            }, //Close Success
            error: function (err) {
                $('#' + divToBeWorkedOn).html("Unavailable");
            }
        }); //Close $.ajax({ 
    }

    </script>

        <script type="text/javascript">
            var webMethod = 'WebService.asmx/GetGameDateRange';
            var gameID = <%= Session["GameID"].ToString().ToLower() %>;
            var parameters = "{'gameID':'" + gameID + "'}";
            var min = '';
            var max = '';

            $.ajax({
                type: "POST",
                url: webMethod,
                data: parameters,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {

                    var game = response.d;
                    if (game != null) {
                        min = game.StartDate;
                        max = game.EndDate;

                        $(function () {
                            $('#txtStartDate').datepick({
                                minDate: min,
                                maxDate: max,
                                dateFormat: 'mm/dd/yyyy',

                                onSelect: function () {
                                    var selected = $('#txtStartDate').datepick({ dateFormat: 'mm/dd/yyyy' }).val();
                                    $("#txtEndDate").datepick("option", "minDate", selected);

                                    var graph = $('[id*=RadioButtonListType]').find('input:checked').val(); 

                                    if(graph == "Graph")
                                        drawGraph();
                                }

                            });

                            $('#txtEndDate').datepick({
                                minDate: min,
                                maxDate: max,
                                dateFormat: 'mm/dd/yyyy',

                                onSelect: function () {
                                    var selected = $('#txtEndDate').datepick({ dateFormat: 'mm/dd/yyyy' }).val();
                                    $("#txtStartDate").datepick("option", "maxDate", selected);

                                    var graph = $('[id*=RadioButtonListType]').find('input:checked').val(); 

                                    if (graph == "Graph")
                                        drawGraph();
                                }

                            });
                        });
                    }
                },
                error: function (err) {
                    $(divToBeWorkedOn).html("Unavailable");
                }

            });                                                                    
</script> 
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
    <span class="style136"><strong><span class="style133">Stock History</span><br />
    </strong></span>
    <table style="width: 100%; height: 42px;" >
            <tr>
                <td class="style135" style="border: thin solid #000000">
                    <strong>&nbsp;List of Stock</strong></td>
                <td class="style4" style="border: thin solid #000000">
                        <asp:Label ID="displaytype_label" runat="server" Font-Bold="False" 
                            ForeColor="Black" Text="Display:"></asp:Label>
                        <asp:RadioButtonList ID="RadioButtonListType" runat="server" 
                            align="center" RepeatDirection="Horizontal" Width="239px" 
                            style="font-size: small" AutoPostBack="True" 
                            onselectedindexchanged="RadioButtonListType_SelectedIndexChanged" 
                            ForeColor="Black">
                            <asp:ListItem Selected="True">Text Based</asp:ListItem>
                            <asp:ListItem>Graph</asp:ListItem>
                            <asp:ListItem>Compare</asp:ListItem>
                        </asp:RadioButtonList>
                    </td>
            </tr>
            <tr style="border: thin solid #000000;">
                    <td class="style135" style="border: thin solid #000000; text-align: center;">
                    <span class="style133">Start Date:
                    <input id="txtStartDate" type="text" readonly="readonly" name="txtStartDate" 
                            align="middle" /></td>
                    <td style="border: thin solid #000000; text-align: center;">
                    <span class="style133">End Date: </span>
                    <input id="txtEndDate" type="text" readonly="readonly" name="txtEndDate" 
                            align="middle" /></td>
           </tr>
</table>

            <div style="height: 63px; text-align: center;">
                <table style="width: 100%; height: 39px;">
                    <tr>
                        <td class="style7" style="border: thin solid #000000;  text-align: center;" 
                            align="right" bgcolor="White">                        
                            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span 
                                class="style134"><span class="style133">Please Select Stock: </span>&nbsp;
                            </span>                        
                            <asp:DropDownList ID="DropDownListComName" runat="server" 
                                AppendDataBoundItems="True" DataSourceID="ShareCompanyNameDataSoruce" 
                                DataTextField="shareName" DataValueField="shareSymbol" Height="20px" 
                                Width="285px" style="text-align: justify" 
                                onselectedindexchanged="DropDownListComName_SelectedIndexChanged" 
                                AutoPostBack="True">
                                <asp:ListItem Value="0">Please Select</asp:ListItem>
                            </asp:DropDownList>
                            &nbsp;
                            <asp:Label ID="tooltip_label" runat="server" ForeColor="Red" 
                                Text="** Stock you own **"></asp:Label>
&nbsp;<asp:SqlDataSource ID="SqlDataSourceStockDetails" runat="server" 
                                    ConnectionString="<%$ ConnectionStrings:stockmarketConnectionString %>" 
                                SelectCommand="GetSharePlotGraph" SelectCommandType="StoredProcedure">
                                    <SelectParameters>
                                        <asp:ControlParameter ControlID="DropDownListComName" Name="ShareSymbol" 
                                            PropertyName="SelectedValue" Type="String" />
                                        <asp:Parameter DefaultValue="1" Name="GameID" Type="Int32" />
                                        <asp:FormParameter DefaultValue="" FormField="txtStartDate" Name="StartDate" Type="String" />
                                        <asp:FormParameter DefaultValue="" FormField="txtEndDate" Name="EndDate" Type="String" />
                                    </SelectParameters>
                                </asp:SqlDataSource>
                        </td>
                    </tr>
                    <tr>
                            <td style="border-style: none; border-width: thin; font-size: small;" 
                                class="style131">
                                <asp:GridView ID="GridViewStockDetails" runat="server" AllowPaging="True" CellPadding="4" 
                                    HorizontalAlign="Center" PageSize="20" AllowSorting="True" Width="887px" 
                                    EnableSortingAndPagingCallbacks="True" ForeColor="#333333" 
                                    AutoGenerateColumns="False" 
                                    DataSourceID="SqlDataSourceStockDetails"> 
                                    
                                    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                                    
                                    <Columns>
                                        <asp:BoundField DataField="HistoryDate" HeaderText="Date" 
                                            ReadOnly="True" SortExpression="HistoryDate" />
                                        <asp:BoundField DataField="OpenValue" HeaderText="Open" 
                                            SortExpression="OpenValue" />
                                        <asp:BoundField DataField="HighValue" HeaderText="High" 
                                            SortExpression="HighValue" />
                                        <asp:BoundField DataField="LowValue" HeaderText="Low" 
                                            SortExpression="LowValue" />
                                        <asp:BoundField DataField="CloseValue" HeaderText="Close" 
                                            SortExpression="CloseValue" />
                                    </Columns>
                                    
                                    <EditRowStyle BackColor="#999999" />
                                    
                                    <FooterStyle BackColor="#5D7B9D" ForeColor="White" Font-Bold="True" />
                                    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                                    <PagerSettings Position="TopAndBottom" />
                                    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                                    <RowStyle ForeColor="#333333" BackColor="#F7F6F3" />
                                    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                                    <SortedAscendingCellStyle BackColor="#E9E7E2" />
                                    <SortedAscendingHeaderStyle BackColor="#506C8C" />
                                    <SortedDescendingCellStyle BackColor="#FFFDF8" />
                                    <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
                                </asp:GridView>
                                <br />
                                </td>
                        </tr>
                </table>
                </div>




<asp:SqlDataSource ID="ShareCompanyNameDataSoruce" runat="server" 
        ConnectionString="<%$ ConnectionStrings:stockmarketConnectionString %>" 
        SelectCommand="RetrieveShareCompanyName" 
    SelectCommandType="StoredProcedure">
    <SelectParameters>
        <asp:SessionParameter Name="UserName" SessionField="UserName" Type="String" />
        <asp:SessionParameter Name="GameID" SessionField="GameID" Type="Int32" 
            DefaultValue="0" />
    </SelectParameters>
    </asp:SqlDataSource>

    <asp:Label ID="zoom_label" runat="server" ForeColor="#FF3300" 
        Text="You can zoom in by drag and drop. Zoom out by double left click" 
        Visible="False"></asp:Label>

<div id="chart2" style="height:400px;width:800px; margin:auto"></div>

    <br />

    </asp:Content>

